<template>
	<view class="new-moent">
		<!-- 输入框 -->
		<view class="text-moment">
			<u-textarea height="120" count placeholder="请输入内容" v-model="inputValue"></u-textarea>
		</view>
		<view class="location-box" @click="getLocation">
			<u-icon name="map" size="20"></u-icon>
			<text>{{locationText}}</text>
		</view>
		<!-- 图片添加 -->
		<view class="imgs">
			<u-upload :fileList="fileList" @afterRead="afterRead" @delete="deletePic" multiple :maxCount="6"
				:previewFullImage="true" width="120" height="120"></u-upload>

		</view>
		<button type="default" @click="doSendMoment">发布</button>

	</view>
</template>

<script>
	import { sendMoment, sendMomentImg } from '@/config/api.js'
	import { mapState } from 'vuex'
	export default {
		data() {
			return {
				inputValue: '',
				fileList: [

				],
				locationText: '点击获取定位'
			}
		},
		onLoad() {

		},
		computed: { ...mapState(['userinfo']) },
		methods: {
			//添加动态
			async doSendMoment() {
				if (this.inputValue.length > 0) {
					uni.showLoading({
						title: '发布中...',
						mask: true
					})

					const { data: res } = await sendMoment({
						userId: this.userinfo.pid,
						text: this.inputValue,
						location: this.locationText === '点击获取定位' ? '' : this.locationText,
					})

					for (let i = 0; i < this.fileList.length; i++) {
						const res2 = await sendMomentImg(this.fileList[i].url, { 'mid': res.mid })
					}
					//模拟上传延迟，完成后返回上一页面并刷新
					setTimeout(() => {
						uni.hideToast()
						uni.navigateBack({
							success: function() {
								uni.$emit('refreshData')
							}
						})
					}, 1000)
				} else {
					uni.showToast({
						title: '您还为未输入文字',
						duration: 1000,
						icon: 'none'
					})
				}
			},
			//删除预上传图片
			deletePic(event) {
				this.fileList.splice(event.index, 1)
			},
			// 新增预上传图片
			async afterRead(event) {
				let lists = [].concat(event.file)
				let fileListLen = this.fileList.length
				lists.map(item => {
					this.fileList.push({
						...item,
						status: 'success',
						message: ''
					})
				})
			},
			getLocation() {
				uni.chooseLocation({
					success: res => {
						this.locationText = res.name
					}
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.new-moent {
		display: flex;
		flex-direction: column;
		margin: 20rpx;

		.text-moment {


			/deep/ .u-textarea__field {
				font-size: 36rpx;
			}
		}

		.location-box {
			display: flex;
			margin-top: 20rpx;

			text {
				color: #828282;
				margin-left: 10rpx;
			}
		}

		.imgs {
			margin-top: 20rpx;
		}
	}
</style>